#coding=utf-8
# Copyright (c) 2016 Tinydot. inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.


import logging
from logging.handlers import RotatingFileHandler

LOGGER_DEFAULT_CONF = {
                       "FORMAT"   : "%(asctime)s [%(name)s-%(levelname)s-%(funcName)s] %(message)s",
                       "LEVEL"    : logging.DEBUG,
                       "IS_DEBUG" : True,
                       "LOG_FILE" : None,
                       "ROOT_NAME": "tbox",
                       }

DEBUG    = logging.DEBUG     # Detailed information, typically of interest only when diagnosing problems.
INFO     = logging.INFO      # Confirmation that things are working as expected.
WARNING  = logging.WARNING   # An indication that something unexpected happened,
ERROR    = logging.ERROR     # Due to a more serious problem, the software has not been able to perform some function.
CRITICAL = logging.CRITICAL #
FATAL    = logging.FATAL

logger_level =    LOGGER_DEFAULT_CONF["LEVEL"]
logger_debug =    LOGGER_DEFAULT_CONF["IS_DEBUG"]
logger_file  =    LOGGER_DEFAULT_CONF["LOG_FILE"]
logfile_handler = None

default_logger = None
def setLevel(level, logger=None):
    ''' Set logger level

        :param level: log level
        :param logger: logger will be set
    '''
    global default_logger, logger_level

    if logger:
        logger.setLevel(level)
        return True
    else:
        if default_logger is not None:
            default_logger.setLevel(level)
            logger_level = level
        return True

def setRoatingLogFile(logile, max_bytes, logger=None):
    """
    set roating log file
    :param logile:
    :param max_bytes:
    :return:
    """
    global default_logger
    _logger = logger or default_logger

    f_handler = RotatingFileHandler(logile, maxBytes=max_bytes, backupCount=1)
    f_handler.setFormatter(logging.Formatter(LOGGER_DEFAULT_CONF["FORMAT"]))
    _logger.addHandler(f_handler)

def getLogger(logname=None):
    '''get loger

       :param name: logger name
    '''
    global logfile_handler, logger_debug, default_logger

    if logname is None:
        if default_logger is not None:
            return default_logger

        logger = logging.getLogger(LOGGER_DEFAULT_CONF["ROOT_NAME"])

        ch = logging.StreamHandler()
        ch.setFormatter(logging.Formatter(LOGGER_DEFAULT_CONF["FORMAT"]))
        logger.addHandler(ch)
        logger.propagate = False
        default_logger = logger
    else:
        logger = logging.getLogger(LOGGER_DEFAULT_CONF["ROOT_NAME"]+"."+logname)
        logger.propagate = True

    logger.setLevel(logger_level)

    if (logger_file is not None) and (logfile_handler is None):
        logfile_handler = logging.FileHandler(logger_file)
        logfile_handler.setFormatter(logging.Formatter(LOGGER_DEFAULT_CONF["FORMAT"]))

    if logfile_handler is not None:
        logger.addHandler(logfile_handler)

    return logger

def setLogFile(log_file, logger=None):
    ''' Set log file

        :param log_file: logfile path
        :param logger: logger
    '''

    global logfile_handler

    logfile_handler = logging.FileHandler(log_file)
    logfile_handler.setFormatter(logging.Formatter(LOGGER_DEFAULT_CONF["FORMAT"]))

    if logger:
        logger.addHandler(logfile_handler)

    return True

def enableDebug(logger=None):
    '''Enable debug
       :param logger: enable whic logger
    '''
    global logger_debug
    logger_debug = True
    if logger:
        logger.propagate = logger_debug

    elif default_logger is not None:
        default_logger.propagate = logger_debug

def disableDebug(logger=None):
    ''' Disable debug
        :param logger: logger to disable
    '''
    global logger_debug, default_logger
    logger_debug = False
    if logger:
        logger.propagate = logger_debug

    elif default_logger is not None:
        default_logger.propagate = logger_debug

LOG = getLogger()
get_logger = getLogger